package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReprotService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.aspectj.weaver.ast.Or;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ReprotServiceImpl implements ReprotService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 获取日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03 dateList
        List<LocalDate> dateList = getDateList(begin, end);

        // 准备营业额列表数据 turnoverList
        ArrayList<Double> turnoverList = new ArrayList<>();

        // 获取营业额，以逗号分隔，例如：406.0,1520.0,75.0 turnoverList
        // 查询orders表，条件：已完成，下单时间
        dateList.forEach(date -> {
            // select sum(amount) from orders where status = 5 and order_time between '2024-05-17' 00:00:00 and 2024-05-17 23:59:49:99999999
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Double turnover = ordersMapper.sumByMap(map);
            // 用来处理没有营业额的情况
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });

        // 构造TurnoverReportVO对象，并返回
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 获取日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03   dateList
        List<LocalDate> dateList = getDateList(begin, end);

        // 新增用户，以逗号分隔，例如：20,21,10  newUserList
        ArrayList<Integer> newUserList = new ArrayList<>();

        // totalUserList数据，总用户列表
        ArrayList<Integer> totalUserList = new ArrayList<>();

        // 循环遍历日期列表统计每日新增用户数--user
        dateList.forEach(date -> {
            // select * from user where create_time between #{} and #{}
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);

            // 用户总量，以逗号分隔，例如：200,210,220  totalUserList
            // select * from user where create_time <= 当天最大值
            map.put("beginTime", null);
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
        });


        //构造 UserReportVO 对象，并返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //获取日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03  dateList
        List<LocalDate> dateList = getDateList(begin, end);

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        //获取每日订单数，以逗号分隔，例如：260,210,215 orderCountList
        // 统计每日orders表数量，条件：下单时间 >= 当天起始时间 and 下单时间 <= 当天结束时间
        // 循环遍历日期列表 进行订单统计
        for (LocalDate date : dateList) {
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer totalOrder = ordersMapper.countByMap(map);
            orderCountList.add(totalOrder);
            //获取有效订单数  validOrderCount
            // 统计每日有效orders表数量，条件：状态=有效(已完成) 下单时间 >= 当天起始时间 and 下单时间 <= 当天结束时间
            map.put("status", Orders.COMPLETED);
            Integer validOrder = ordersMapper.countByMap(map);
            validOrderCountList.add(validOrder);

            //获取区间的订单总数 totalOrderCount
            // select count(*) from orders where 下单时间 >= ‘2024-5.14 00:00:00’ 下单时间 <= '2024-5.20 23:59:59:99999'
            totalOrderCount += totalOrder;

            //获取每日有效订单数，以逗号分隔，例如：20,21,10  validOrderCountList
            validOrderCount += validOrder;
        }


        //计算订单完成率  orderCompletionRate
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = (validOrderCount + 0.0) / totalOrderCount;
        }

        // 构造 OrderReportVO 对象，并返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销售排名Top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 获取商品名称列表，根据时间选择区间，展示销量前10的商品(包含菜品和套餐) nameList
        List<String> nameList = new ArrayList<>();

        // 构造销量列表，以逗号分隔，例如：260,215,200 numberList
        List<Integer> numberList = new ArrayList<>();

        // 查询订单明细表order_detail 加 订单表orders,条件：订单状态-已完成，下单时间
        Map map = new HashMap();
        map.put("status",Orders.COMPLETED);
        map.put("beginTime",LocalDateTime.of(begin,LocalTime.MIN));
        map.put("endTime",LocalDateTime.of(end,LocalTime.MAX));

        List<GoodsSalesDTO> list = ordersMapper.sumTop10(map);

        for (GoodsSalesDTO dto : list) {
            nameList.add(dto.getName());
            numberList.add(dto.getNumber());
        }



        // 构造 SalesTop10ReportVO 对象，并返回
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(nameList,","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        // 1.查询近30天的运营数据
        LocalDate now = LocalDate.now();        // 2024-05-23
        LocalDate end = now.minusDays(1); // 2024-05-22
        LocalDate begin = now.minusDays(30);    // 2024-04-22
        // LocalDateTime end =
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        ClassPathResource classPathResource = new ClassPathResource("template/运营数据报表模板.xlsx");
        InputStream is ;

        //获取流
        try {
             is = classPathResource.getInputStream();
            // 2.往Excel表中写入数据
            // 根据类加载器读取项目中的模板文件, 基于模板文件创建Excel对象
             //is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());    //营业额
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());    //订单完成率
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());    //新增用户数

            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount()); //有效订单
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());       //平均客单价

            // 30天明细数据填充
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                beginTime = LocalDateTime.of(date, LocalTime.MIN); //4-23 00:00
                endTime = LocalDateTime.of(date, LocalTime.MAX);   //4-23 23:59:59.999999
                businessData = workspaceService.getBusinessData(beginTime, endTime);

                sheet.getRow(7+i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7+i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7+i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(7+i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7+i).getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 3.通过输出流将Excel文件对象下载到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);

            // 4.释放资源
            os.close();
            workbook.close();
            is.close();
        } catch (IOException e) {
            log.error("文件写入失败！！！{}",e.getMessage());
        }
    }


    /**
     * 获取日期列表数据
     * @param begin
     * @param end
     * @return
     */

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<LocalDate>();
        // 循环插入日期数据
        while (!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        log.info("dataList = {}", dateList);
        return dateList;
    }
}
